/*
 * @Author: kanglang
 * @Date: 2021-02-23 11:22:57
 * @LastEditors: zeki mini
 * @LastEditTime: 2021-06-10 15:46:16
 * @Description: 第二步 -- 填写法人信息
 */

import React from 'react';
import { View, StyleSheet, Text, ScrollView, NativeModules, SafeAreaView, PixelRatio } from 'react-native';
import { Button, msg, FormInput, AsyncStorage, cache } from '@/common';
import {
  px2dp, priceColor, mainBgColorWhite, fontColorBlack,
  fontColorDeepGray, mainBgColorLightGray, mainBgColorBlack
} from '@/styles';
import { defaultIdCardFront, defaultIdCardBack } from '@/images';
import DateTimePicker from 'react-native-modal-datetime-picker';
import Moment from 'moment';
import { uploadImage } from '@/config';
import CameraCard from './components/camera-card';
import BusinessDateItem from './components/business-date-item';

const { Submit } = Button;

export default class BusinessInfoCerti extends React.Component {
  constructor(props) {
    super(props);
    const { navigation } = props;
    const state = navigation.state || {};
    const params = state.params || {};
    const { routerFrom } = params;
    this.state = {
      longTimeChecked: false,
      selectDateChecked: false,
      isTimeShow: false,
      type: '居民身份证',
      name: '',
      idNo: '',
      validStartDate: '',
      validEndDate: '',
      identityCardFrontId: '',
      identityCardBackId: '',
      routerFrom
    };
  }

  componentDidMount() {
    AsyncStorage.getItem(cache.LEGAL_INFO_CERTI).then((data) => {
      const dataCache = JSON.parse(data) || {};
      const { legalInfoCerti } = dataCache;
      this.setState({ ...legalInfoCerti });
    }).catch(err => {
      console.log('法人信息反写异常：', err);
    });
  }

  render() {
    const { type, name, idNo, longTimeChecked, isTimeShow, validStartDate, validEndDate,
      identityCardFrontId, identityCardBackId, selectDateChecked } = this.state;
    return (
      <SafeAreaView style={styles.container}>
        <ScrollView style={styles.inner}>
          <Text style={styles.stepTip}>第二步</Text>
          <View style={styles.firstPart}>
            <FormInput
              label={<>
                <Text style={{ color: priceColor }}>&nbsp;&nbsp;</Text>
                <Text style={{ color: fontColorDeepGray, fontSize: px2dp(28) }}>证件类型</Text>
              </>}
              labelWidth={{ width: px2dp(200) }}
              placeholder='请选择证件类型'
              defaultValue={type}
              inputType={1}
              textStyles={{ textAlign: 'left' }}
              boxStyle={{ height: 60, paddingLeft: 0 }}
              onChange={(value) => {
                this.onChange('type', value);
              }}
            />
            <FormInput
              label={this.formItem('姓名')}
              labelWidth={{ width: px2dp(200) }}
              placeholder='请输入姓名'
              defaultValue={name}
              inputType={1}
              textStyles={{ textAlign: 'left' }}
              boxStyle={{ height: 60, paddingLeft: 0 }}
              onChange={(value) => {
                this.onChange('name', value);
              }}
            />

            <FormInput
              label={this.formItem('证件号码')}
              labelWidth={{ width: px2dp(200) }}
              placeholder='请输入证件号码'
              defaultValue={idNo}
              inputType={1}
              maxLength={18}
              textStyles={{ textAlign: 'left' }}
              boxStyle={{ minHeight: 60, borderBottomColor: 'transparent', paddingLeft: 0 }}
              onChange={(value) => {
                this.onChange('idNo', value);
              }}
            />
            <BusinessDateItem
              label='有效期限'
              selectDateChecked={selectDateChecked}
              longTimeChecked={longTimeChecked}
              onSwitchLongTime={this.switchChecked}
              onSwitchSelectDate={this.switchDateChecked}
              onStartDate={() => {
                this.setState({ isTimeShow: true, isTimeType: 'validStartDate' });
              }}
              onEndDate={() => {
                this.setState({ isTimeShow: true, isTimeType: 'validEndDate' });
              }}
              startTip={validStartDate}
              endTip={validEndDate}
            />
          </View>
          <View style={styles.licenseBox}>
            <View style={styles.labelBox}>{this.formItem('添加身份证')}</View>
            <View style={styles.idcardBtnBox}>
              <CameraCard
                title='点击拍摄或上传人像面'
                type='identityCardFrontId'
                icon={identityCardFrontId}
                onCatchImage={(type) => this.selectImage(type)}
                bgImage={defaultIdCardFront}
              />
              <CameraCard
                title='点击拍摄或上传国徽面'
                type='identityCardBackId'
                icon={identityCardBackId}
                onCatchImage={(type) => this.selectImage(type)}
                bgImage={defaultIdCardBack}
              />
            </View>

          </View>
          <View style={styles.bottomBtnBox}>
            <View style={styles.submitBox}>
              <Submit
                text='上一步'
                btnTextStyle={styles.preStepText}
                boxStyle={styles.preBoxStyle}
                onClick={this.goBack}
              />
            </View>
            <View style={styles.submitBox}>
              <Submit
                text='下一步'
                btnTextStyle={styles.nextStepText}
                boxStyle={styles.nextBoxStyle}
                onClick={this.goNext}
              />
            </View>
          </View>
          <DateTimePicker
            isVisible={isTimeShow}
            mode='date'
            cancelTextIOS='取消'
            confirmTextIOS='确认'
            headerTextIOS='选取日期'
            locale='zh_CN'
            onConfirm={(val) => {
              this.dateConfirm(val);
            }}
            onCancel={() => {
              this.dateCancel();
            }}
          />
        </ScrollView>
      </SafeAreaView>
    );
  }

  formItem = (name) => {
    return (
      <>
        <Text style={{ color: priceColor }}>＊</Text>
        <Text style={{ color: fontColorDeepGray, fontSize: px2dp(28) }}>{name}</Text>
      </>
    );
  }

  // 选择长期
  switchChecked = () => {
    const { longTimeChecked } = this.state;
    this.setState({ longTimeChecked: !longTimeChecked }, () => {
      const { longTimeChecked } = this.state;
      if (longTimeChecked) {
        this.setState({ selectDateChecked: false, validEndDate: '长期' });
      }
    });
  }

  // 选择日期
  switchDateChecked = () => {
    const { selectDateChecked } = this.state;
    this.setState({ selectDateChecked: !selectDateChecked, longTimeChecked: false }, () => {
      const { selectDateChecked } = this.state;
      if (!selectDateChecked) {
        this.setState({ validStartDate: '', validEndDate: '' });
      } else {
        this.setState({ validEndDate: '' });
      }
    });
  }

  goBack = () => {
    msg.emit('router: back');
  }

  goNext = () => {
    const { type, name, idNo, longTimeChecked, validStartDate, validEndDate,
      identityCardFrontId, identityCardBackId, selectDateChecked, routerFrom } = this.state;
    if (!type) return msg.emit('app:tip', { text: '请选择证件类型' });
    if (!name) return msg.emit('app:tip', { text: '请填写用户姓名' });
    if (!idNo) return msg.emit('app:tip', { text: '请填写证件号码' });
    if (idNo && idNo.length != 15 && idNo.length != 18) return msg.emit('app:tip', { text: '请填写正确的身份证号码' });
    if ((!validStartDate || !validEndDate) && !longTimeChecked) return msg.emit('app:tip', { text: '请选择有效期限' });
    if (longTimeChecked && !validStartDate) return msg.emit('app:tip', { text: '请选择有效期限起始日期' });
    if (!identityCardFrontId) return msg.emit('app:tip', { text: '请上传证件照正面' });
    if (!identityCardBackId) return msg.emit('app:tip', { text: '请上传证件照背面' });

    const legalInfoCertiCache = {
      type,
      name,
      idNo,
      validStartDate,
      validEndDate,
      longTimeChecked, // 是否选择长期
      selectDateChecked, // 是否选择了日期
      longTime: longTimeChecked ? 1 : 0,
      identityCardFrontId,
      identityCardBackId
    };
    const businessCertiString = JSON.stringify({
      legalInfoCerti: legalInfoCertiCache
    });
    AsyncStorage.setItem(
      cache.LEGAL_INFO_CERTI,
      businessCertiString
    );

    msg.emit('router: goToNext', {
      routeName: 'CorporateAccountInfoCerti',
      routerFrom
    });
  }

  // 输入框变化监听
  onChange = (type, value) => {
    this.setState({ [type]: value });
  }

  // 日期选择后确认
  dateConfirm = (date) => {
    const { isTimeType } = this.state;
    this.setState({ [isTimeType]: Moment(date).format('YYYY-MM-DD') });
    this.setState({ isTimeShow: false });
  }

  // 隐藏日期选择器
  dateCancel = () => {
    this.setState({ isTimeShow: false });
  };

  // 选择图片
  selectImage = imgType => {
    NativeModules.DataModule.chooseImage((path, imageBase64) => {
      this.IdCardUpload(imgType, path);
    });
  }

  // 上传图片
  IdCardUpload(imgType, path) {
    msg.emit('app:selfTip', {
      isVisible: true,
      text: '图片上传中...',
      icon: 'loading',
      style: { zIndex: 1 }
    });
    uploadImage('upload?dirName=businessCert', path).then(res => {
      if (res.success) {
        if (imgType === 'identityCardFrontId') {
          this.setState({ identityCardFrontId: res.data.url });
        }
        if (imgType === 'identityCardBackId') {
          this.setState({ identityCardBackId: res.data.url });
        }
      } else {
        msg.emit('app:messageBox', {
          isVisible: true,
          title: '温馨提示',
          text: '上传失败，请重试',

          isClickBg: false,
          okFn: () => { },
        });
      }
      msg.emit('app:selfTip', {
        isVisible: false,
      });
    }).catch(err => {
      console.log(err);
      msg.emit('app:selfTip', {
        isVisible: false,
      });
      // 请求失败
      msg.emit('app:messageBox', {
        isVisible: true,
        title: '温馨提示',
        text: '上传失败，请重试',

        isClickBg: false,
        okFn: () => { },
      });
    });
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: mainBgColorWhite,
  },
  inner: {
    flex: 1,
    backgroundColor: mainBgColorLightGray
  },
  stepTip: {
    color: mainBgColorBlack,
    fontSize: px2dp(28),
    paddingLeft: px2dp(32),
    paddingVertical: px2dp(24)
  },
  firstPart: {
    backgroundColor: mainBgColorWhite,
    paddingHorizontal: px2dp(32),
    paddingBottom: px2dp(60)
  },
  fontTitle: {
    color: fontColorBlack,
    fontSize: px2dp(32),
    marginTop: px2dp(32),
    lineHeight: px2dp(40)
  },
  fontText: {
    color: fontColorBlack,
    fontSize: px2dp(28),
    lineHeight: px2dp(38)
  },
  tempText: {
    color: '#2293FF',
    fontSize: px2dp(28),
    textDecorationLine: 'underline'
  },
  btnBox: {
    flex: 1,
    alignItems: 'center',
    marginTop: px2dp(130)
  },
  boxStyle: {
    width: px2dp(640),
    height: px2dp(96),
    borderRadius: px2dp(12),
    overflow: 'hidden',
  },
  longTimeBox: {
    flexDirection: 'row',
    marginRight: px2dp(40)
  },
  longTime: {
    color: '#b2b2b2',
    marginLeft: px2dp(16)
  },
  itemBox: {
    flexDirection: 'row',
    alignItems: 'center',
    borderBottomWidth: 1 / PixelRatio.get(),
    borderBottomColor: '#ebebeb',
    width: '100%',
    height: 60,
  },
  labelBox: {
    flexDirection: 'row',
    alignItems: 'center',
    width: px2dp(190)
  },
  addressBox: {
    flexDirection: 'row',
    alignItems: 'center',
    marginLeft: px2dp(10)
  },
  addressImgBox: {
    flexDirection: 'row',
    alignItems: 'center'
  },
  iconMore: {
    width: px2dp(24),
    height: px2dp(24),
    marginLeft: px2dp(16)
  },
  timeImg: {
    width: px2dp(36),
    height: px2dp(36),
    marginRight: px2dp(16)
  },
  licenseBox: {
    justifyContent: 'space-between',
    backgroundColor: mainBgColorWhite,
    paddingHorizontal: px2dp(32),
    paddingVertical: px2dp(40),
    marginTop: px2dp(24),
  },
  idcardBtnBox: {
    width: '100%',
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    marginTop: px2dp(40),

  },
  licenseImgStyle: {
    width: px2dp(160),
    height: px2dp(160),
  },
  defaultAddBox: {
    width: px2dp(160),
    height: px2dp(160),
    backgroundColor: mainBgColorLightGray,
    justifyContent: 'center',
    alignItems: 'center',
    borderRadius: px2dp(8),
  },
  addImgIcon: {
    width: px2dp(48),
    height: px2dp(48)
  },
  bottomBtnBox: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'center',
    marginTop: px2dp(40),
    height: px2dp(200),
  },
  submitBox: {
    flex: 1,
    alignItems: 'center'
  },
  preStepText: {
    fontSize: px2dp(32),
    color: '#686764'
  },
  nextStepText: {
    fontSize: px2dp(32),
  },
  preBoxStyle: {
    width: px2dp(280),
    borderRadius: px2dp(12),
    backgroundColor: '#E6E6E5'
  },
  nextBoxStyle: {
    width: px2dp(280),
    borderRadius: px2dp(12),
  },
  addressText: {
    color: '#b2b2b2',
    maxWidth: '80%'
  },
});
